<template>
  <div class="container">
    <a-card class="general-card" :title="$route.meta.locale">
      <table-search
        v-permission="'patient:list:query'"
        :fileds="searchFileds"
        @search="search"
        @reset="search"
      ></table-search>
      <xTable
        v-model:refresh="refresh"
        v-model:selected-keys="selectedKeys"
        :params="params"
        :columns="tableColumns"
        :http="{
          list: getDataList,
          del: removePatientAll,
          batchDel: removePatientAlls,
        }"
        :http-permission="{
          del: 'patient:list:del',
          batchDel: 'patient:list:batchDel',
        }"
        :import-config="importConfig"
        row-key="userId"
      >
        <template #operation-default>
          <div v-permission="'patient:list:add'" class="item">
            <a-button type="outline" @click="editOpen(null)"> 新增 </a-button>
          </div>
        </template>
        <template #sex="{ row }">
          <dict-tag :options="dict.sys_user_sex" :value="row.sex" />
        </template>
        <template #patientType="{ row }">
          <dict-tag :options="dict.disease_label" :value="row.patientType" />
        </template>
        <template #travelPath="{ row }">
          <router-link
            :to="{
              name: 'PatientMap',
              params: { id: row.userId, name: row.nickName },
            }"
            class="link-type"
          >
            <span>查看</span>
          </router-link>
        </template>
        <template #optional="{ row }">
          <router-link
            :to="{
              name: 'PatientDetail',
              params: { id: row.userId, name: row.nickName, tab: '1' },
            }"
          >
            <a-button type="text">查看</a-button>
          </router-link>
          <a-button
            v-permission="'patient:list:edit'"
            type="text"
            status="success"
            @click="editOpen(-1, row)"
          >
            编辑
          </a-button>
        </template>
      </xTable>
    </a-card>
    <!-- m-tag="a-drawer" -->
    <EditModal
      ref="edit"
      :default-value="defValue"
      width="750px"
      :fields="editFields"
      :http-add="addPatientAll"
      :http-edit="updatePatientAll"
      :handler="handler"
      @reload="refresh = true"
    >
    </EditModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { getDict } from '@/utils/dict';
  import { birthdayToAge } from '@/utils';
  import {
    getDataList,
    addPatientAll,
    removePatientAll,
    removePatientAlls,
    updatePatientAll,
  } from '@/api/patient';
  import { dictType, patientImportTemplate } from '@/api/exportFile';
  import { treeselect as deptTreeSelect } from '@/api/system/dept';
  import getPageConfig from './config';

  const dict = getDict('sys_user_sex', 'disease_label');
  const edit = ref();
  const deptTree = ref([]);
  const pageConfig = getPageConfig({
    sys_user_sex: dict.sys_user_sex,
    disease_label: dict.disease_label,
    deptTree,
  });
  const selectedKeys: any = ref([]);
  const searchFileds = reactive(pageConfig.searchFileds);
  const tableColumns = reactive(pageConfig.tableColumns);
  const editFields = reactive(pageConfig.editFields);
  const importConfig: any = ref({
    url: `${
      import.meta.env.VITE_API_BASE_URL
    }/system/ExcelSheetImportController/patientImport`,
    title: '导入患者',
    width: '500px',
    template: patientImportTemplate,
    permission: 'system:user:import',
  });
  const defValue = ref({
    password: '123456',
  });
  const refresh = ref(true);
  // 定义表格查询参数
  const params = ref({
    dateRange: [],
  });
  // 定义搜索方法
  const search = (data: any) => {
    params.value = data;
    refresh.value = true;
  };
  const editOpen = async (keys: any | any[], value?: any) => {
    if (value) {
      edit.value.show(value.userId, value);
    } else if (Array.isArray(keys) && keys.length === 1) {
      edit.value.show(keys[0]);
    } else if (!Array.isArray(keys)) {
      edit.value.show(keys);
    } else if (Array.isArray(keys) && keys.length < 1) {
      Message.warning('必须选中一条数据');
    } else if (Array.isArray(keys) && keys.length > 1) {
      Message.warning('只能选中一条数据');
    }
  };

  const handler = (data: any) => {
    if (data.dateOfBirth) {
      data.age = birthdayToAge(data.dateOfBirth);
    }
    return {
      ...data,
      userWeight: data.userWeight ? Number(data.userWeight) : 0,
      userHeight: data.userHeight ? Number(data.userHeight) : 0,
      user_type: '01',
    };
  };
  const initSelectData = async () => {
    const deptRes = await deptTreeSelect();
    if (deptRes.code !== 200) {
      Message.error(deptRes.msg);
      return;
    }
    deptTree.value = deptRes.data;
  };
  initSelectData();
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
